﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DungeonCraft.DataModel.Interfaces;
using System.Windows.Forms;

namespace DungeonCraft.DataModel.Tools
{
    public class CallbackTimer : ICallbackTimer
    {
        private Timer timer;
        private Action endCallBack;
        private Action tickCallback;
        private int numberOfTicks;
        private int currentTick;
        private EventHandler tickEventHandler;

        public int NumberOfTicks { get { return numberOfTicks; } set { numberOfTicks = value; } }
        public int tickTime
        {
            get
            {
                return timer.Interval;
            }
            set
            {
                timer.Interval = value;
            }
        }

        public CallbackTimer()
        {
            timer = new Timer();
        }

        public CallbackTimer(int tickTime, int numberOfTicks)
        {
            timer = new Timer();
            timer.Interval = tickTime;
            this.numberOfTicks = numberOfTicks;
        }



        private void runTickCallback(object caller, EventArgs e)
        {
            if (numberOfTicks != 0)
                if (currentTick == numberOfTicks)
                {

                    timer.Stop();
                    if (endCallBack != null)
                        endCallBack.Invoke();
                    return;
                }
            if (tickCallback != null)
                tickCallback.Invoke();
            currentTick++;
        }

        public void Start()
        {
            if (tickCallback == null)
                tickEventHandler = new EventHandler(runTickCallback);
            timer.Tick += tickEventHandler;
            timer.Start();

        }

        public Action EndCallBack
        {
            get
            {
                return endCallBack;
            }
            set
            {
                endCallBack = value;
            }
        }

        public Action TickCallBack
        {
            get
            {
                return tickCallback;
            }
            set
            {
                tickCallback = value;
                tickEventHandler = new EventHandler(runTickCallback);
            }
        }

        public void Reset()
        {
            currentTick = 0;
            timer.Tick -= tickEventHandler;
        }

        public int CurrentTick
        {
            get
            {
                return currentTick;
            }
            set
            {
                currentTick = value;
            }

        }



    }
}
